use crate::controller::Error;
use crate::dto;
use crate::service::ServiceSet;
use std::sync::Arc;

pub struct TePolicyGroupController {
    service_set: Arc<ServiceSet>,
}

impl TePolicyGroupController {
    pub fn new(service_set: Arc<ServiceSet>) -> Self {
        Self { service_set }
    }
    pub async fn add(
        &self,
        request: &dto::te_policy_group::AddRequest,
    ) -> Result<dto::core::te_policy_group::AddResponseData, Error> {
        let data = self.service_set.te_policy_group.add(request).await?;

        Ok(data)
    }

    pub async fn list(
        &self,
        request: &dto::te_policy_group::ListRequest,
    ) -> Result<dto::te_policy_group::ListResponseData, Error> {
        let total_count = self
            .service_set
            .te_policy_group
            .count(&request.filter)
            .await?;

        if total_count == 0 {
            return Ok(dto::te_policy_group::ListResponseData {
                total_count: 0,
                list: Vec::new(),
            });
        }

        let list = self
            .service_set
            .te_policy_group
            .list(&request.filter, request.offset, request.limit)
            .await?;

        Ok(dto::te_policy_group::ListResponseData { total_count, list })
    }
    
    pub async fn get(
        &self,
        request: &dto::te_policy_group::GetRequest,
    ) -> Result<dto::core::te_policy_group::TePolicyGroupItem, Error> {
        let data = self.service_set.te_policy_group.get(request.te_policy_group_id.as_str()).await?;

        Ok(data)
    }
    
    pub async fn update(
        &self,
        request: &dto::te_policy_group::UpdateRequest,
    ) -> Result<(), Error> {
        if request.params == Default::default() {
            return Ok(());
        }
        
        self
            .service_set
            .te_policy_group
            .update(request.te_policy_group_id.as_str(), &request.params)
            .await?;
        
        Ok(())
    }
    
    pub async fn delete(
        &self,
        request: &dto::te_policy_group::DeleteRequest,
    ) -> Result<(), Error> {
        self
            .service_set
            .te_policy_group
            .delete(request.te_policy_group_id.as_str())
            .await?;
        
        Ok(())
    }
}
